import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../base_notifier.dart';
import 'user_notifier.dart';
import 'todo_list_notifier.dart';
import 'async_user_notifier.dart';

// UI 组件示例 - 展示如何在 Widget 中使用基类
class UserProfilePage extends ConsumerWidget {
  const UserProfilePage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final userState = ref.watch(userProvider);

    return Scaffold(
      appBar: AppBar(
        title: const Text('用户资料'),
        actions: [
          IconButton(
            onPressed: () {
              ref.read(userProvider.notifier).refresh();
            },
            icon: const Icon(Icons.refresh),
          ),
        ],
      ),
      body: _buildBody(context, ref, userState),
    );
  }

  Widget _buildBody(BuildContext context, WidgetRef ref, BaseState<User> state) {
    if (state.isLoading && !state.isRefreshing) {
      return const Center(child: CircularProgressIndicator());
    }

    if (state.isError && !state.hasData) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(Icons.error, size: 64, color: Colors.red),
            const SizedBox(height: 16),
            Text('错误: ${state.error}'),
            const SizedBox(height: 16),
            ElevatedButton(
              onPressed: () {
                ref.read(userProvider.notifier).loadData();
              },
              child: const Text('重试'),
            ),
          ],
        ),
      );
    }

    if (state.isEmpty) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.person_off, size: 64, color: Colors.grey),
            SizedBox(height: 16),
            Text('暂无用户数据'),
          ],
        ),
      );
    }

    if (state.isSuccess && state.hasData) {
      final user = state.data!;
      return Stack(
        children: [
          Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              children: [
                Card(
                  child: ListTile(
                    leading: const CircleAvatar(child: Icon(Icons.person)),
                    title: Text(user.name),
                    subtitle: Text(user.email),
                    trailing: Text('ID: ${user.id}'),
                  ),
                ),
                const SizedBox(height: 16),
                ElevatedButton(
                  onPressed: () {
                    final updatedUser = User(
                      id: user.id,
                      name: '${user.name} (已更新)',
                      email: user.email,
                    );
                    ref.read(userProvider.notifier).updateUser(updatedUser);
                  },
                  child: const Text('更新用户信息'),
                ),
              ],
            ),
          ),
          if (state.isRefreshing)
            const Positioned(
              top: 0,
              left: 0,
              right: 0,
              child: LinearProgressIndicator(),
            ),
        ],
      );
    }

    return const Center(child: Text('未知状态'));
  }
}

// Todo 列表页面
class TodoListPage extends ConsumerWidget {
  const TodoListPage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final todoState = ref.watch(todoListProvider);
    final uncompletedCount = ref.watch(uncompletedTodoCountProvider);

    return Scaffold(
      appBar: AppBar(
        title: Text('待办事项 ($uncompletedCount)'),
        actions: [
          IconButton(
            onPressed: () {
              ref.read(todoListProvider.notifier).refresh();
            },
            icon: const Icon(Icons.refresh),
          ),
        ],
      ),
      body: _buildTodoBody(context, ref, todoState),
      floatingActionButton: FloatingActionButton(
        onPressed: () => _showAddTodoDialog(context, ref),
        child: const Icon(Icons.add),
      ),
    );
  }

  Widget _buildTodoBody(BuildContext context, WidgetRef ref, BaseState<List<Todo>> state) {
    if (state.isLoading && !state.isRefreshing) {
      return const Center(child: CircularProgressIndicator());
    }

    if (state.isError && !state.hasData) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(Icons.error, size: 64, color: Colors.red),
            Text('错误: ${state.error}'),
            ElevatedButton(
              onPressed: () => ref.read(todoListProvider.notifier).loadData(),
              child: const Text('重试'),
            ),
          ],
        ),
      );
    }

    if (state.isEmpty) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.check_circle_outline, size: 64, color: Colors.green),
            Text('暂无待办事项'),
          ],
        ),
      );
    }

    if (state.hasData) {
      final todos = state.data!;
      return Column(
        children: [
          if (state.isRefreshing) const LinearProgressIndicator(),
          Expanded(
            child: ListView.builder(
              itemCount: todos.length,
              itemBuilder: (context, index) {
                final todo = todos[index];
                return ListTile(
                  leading: Checkbox(
                    value: todo.isCompleted,
                    onChanged: (_) {
                      ref.read(todoListProvider.notifier).toggleTodo(todo.id);
                    },
                  ),
                  title: Text(
                    todo.title,
                    style: TextStyle(
                      decoration: todo.isCompleted
                          ? TextDecoration.lineThrough
                          : TextDecoration.none,
                    ),
                  ),
                  trailing: IconButton(
                    icon: const Icon(Icons.delete),
                    onPressed: () {
                      ref.read(todoListProvider.notifier).deleteTodo(todo.id);
                    },
                  ),
                );
              },
            ),
          ),
        ],
      );
    }

    return const Center(child: Text('未知状态'));
  }

  void _showAddTodoDialog(BuildContext context, WidgetRef ref) {
    final controller = TextEditingController();

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('添加待办事项'),
        content: TextField(
          controller: controller,
          decoration: const InputDecoration(hintText: '请输入待办事项'),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              if (controller.text.isNotEmpty) {
                ref.read(todoListProvider.notifier).addTodo(controller.text);
                Navigator.pop(context);
              }
            },
            child: const Text('添加'),
          ),
        ],
      ),
    );
  }
}

// 异步用户资料页面
class AsyncUserProfilePage extends ConsumerWidget {
  const AsyncUserProfilePage({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final userState = ref.watch(asyncUserProfileProvider);
    final displayName = ref.watch(userDisplayNameProvider);

    return Scaffold(
      appBar: AppBar(
        title: Text('用户资料 - $displayName'),
      ),
      body: userState.when(
        data: (state) => _buildAsyncUserBody(context, ref, state),
        loading: () => const Center(child: CircularProgressIndicator()),
        error: (error, _) => Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Icon(Icons.error, size: 64, color: Colors.red),
              Text('加载失败: $error'),
              ElevatedButton(
                onPressed: () {
                  ref.invalidate(asyncUserProfileProvider);
                },
                child: const Text('重试'),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildAsyncUserBody(BuildContext context, WidgetRef ref, BaseState<UserProfile> state) {
    if (state.isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    if (state.isError) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('错误: ${state.error}'),
            ElevatedButton(
              onPressed: () {
                ref.read(asyncUserProfileProvider.notifier).refresh();
              },
              child: const Text('重试'),
            ),
          ],
        ),
      );
    }

    if (state.hasData) {
      final user = state.data!;
      return Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            Card(
              child: Padding(
                padding: const EdgeInsets.all(16),
                child: Column(
                  children: [
                    CircleAvatar(
                      radius: 50,
                      backgroundImage: NetworkImage(user.avatar),
                    ),
                    const SizedBox(height: 16),
                    Text(
                      user.name,
                      style: Theme.of(context).textTheme.headlineSmall,
                    ),
                    Text(user.email),
                    const SizedBox(height: 8),
                    Text('最后登录: ${user.lastLogin.toString().substring(0, 19)}'),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),
            Row(
              children: [
                Expanded(
                  child: ElevatedButton(
                    onPressed: () {
                      ref.read(asyncUserProfileProvider.notifier).updateProfile(
                        name: '${user.name} (已更新)',
                      );
                    },
                    child: const Text('更新姓名'),
                  ),
                ),
                const SizedBox(width: 8),
                Expanded(
                  child: ElevatedButton(
                    onPressed: () {
                      ref.read(asyncUserProfileProvider.notifier).refresh();
                    },
                    child: const Text('刷新'),
                  ),
                ),
              ],
            ),
          ],
        ),
      );
    }

    return const Center(child: Text('暂无数据'));
  }
}

// 主页面 - 展示所有示例
class ExampleHomePage extends StatelessWidget {
  const ExampleHomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Riverpod 状态管理示例'),
      ),
      body: ListView(
        padding: const EdgeInsets.all(16),
        children: [
          _buildExampleCard(
            context,
            title: '用户资料管理',
            description: '展示基础状态管理，包括加载、成功、错误状态',
            onTap: () => _navigateTo(context, const UserProfilePage()),
          ),
          _buildExampleCard(
            context,
            title: '待办事项列表',
            description: '展示列表数据管理，包括空数据状态处理',
            onTap: () => _navigateTo(context, const TodoListPage()),
          ),
          _buildExampleCard(
            context,
            title: '异步用户资料',
            description: '展示异步初始化的状态管理',
            onTap: () => _navigateTo(context, const AsyncUserProfilePage()),
          ),
        ],
      ),
    );
  }

  Widget _buildExampleCard(
    BuildContext context, {
    required String title,
    required String description,
    required VoidCallback onTap,
  }) {
    return Card(
      margin: const EdgeInsets.only(bottom: 16),
      child: ListTile(
        title: Text(title),
        subtitle: Text(description),
        trailing: const Icon(Icons.arrow_forward_ios),
        onTap: onTap,
      ),
    );
  }

  void _navigateTo(BuildContext context, Widget page) {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => page),
    );
  }
}